package com.xjw.hospital.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.cron.CronUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xjw.annotation.FXController;
import com.xjw.annotation.FXRedirect;
import com.xjw.annotation.FXWindow;
import com.xjw.coreutil.cache.CacheUtil;
import com.xjw.coreutil.common.PropUtil;
import com.xjw.coreutil.common.StringUtil;
import com.xjw.entity.FXBaseController;
import com.xjw.hospital.entity.DocInfo;
import com.xjw.hospital.utils.ToolUtil;
import com.xjw.utils.JavaFXType;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TableView;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;

/**
 * @author 徐军文
 * @since 2022/8/10 22:43
 */
@FXController(path = "fxml/main.fxml")
@FXWindow(title = "首页", icon = "image/icon.png", mainStage = true)
public class MainController extends FXBaseController implements Initializable {

    @FXML
    private TextField nameEle;

    @FXML
    private TableView<DocInfo> docsEle;

    @FXML
    private TextArea msgEle;

    @FXML
    private TextField tokenEle;

    private final StringBuilder msgstb = new StringBuilder();

    private final PropUtil propUtil = PropUtil.getInstance(PropUtil.USERDATA);

    private final ObservableList<DocInfo> docs = FXCollections.observableArrayList();

    private final Log logger = LogFactory.get();

    public void initialize(URL location, ResourceBundle resources) {
        CronUtil.start();
        CronUtil.setMatchSecond(true);
        docsEle.setItems(docs);
        tokenEle.setText(propUtil.getStr("token"));
        nameEle.setText( propUtil.getChStr("name"));
        initMsgTool();
    }

    private void initMsgTool() {
        CacheUtil.put("msgs", new ArrayList<String>(50));
        ThreadUtil.execAsync(() -> {
            while (!JavaFXType.isStopFlag()) {
                try {
                    List<String> msgCache = CacheUtil.get("msgCache");
                    if (msgCache == null) {
                        msgCache = new ArrayList<>(100);
                        CacheUtil.put("msgCache", msgCache);
                    }
                    if (!msgCache.isEmpty()) {
                        for (int i = msgCache.size() - 1;i >= 0;i--) {
                            setMsg(msgCache.remove(i));
                        }
                    }
                    ThreadUtil.sleep(200);
                } catch (RuntimeException e) {
                    logger.error("fail to show msg", e);
                }
            }
        });
    }

    @FXML
    private void searchDoc() {
        String name = nameEle.getText();
        if (!StringUtil.isEmpty(name)) {
            if (StringUtil.isEmpty(tokenEle.getText())) {
                setMsg("请输入token");
                return;
            }
            ToolUtil.setToken(tokenEle.getText());
            propUtil.setProperty("token", ToolUtil.getToken());
            propUtil.setChStr("name", name);
            propUtil.store();
            JSONArray datas = ToolUtil.searchDoc(name);
            docs.clear();
            for (int i = 0;i < datas.size();i++) {
                JSONObject docInfoJson = datas.getJSONObject(i);
                DocInfo docInfo = new DocInfo();
                docInfo.setDocInfoJson(docInfoJson);
                docInfo.setDocId(docInfoJson.getString("docId"));
                docInfo.setDocName(docInfoJson.getString("docName"));
                docInfo.setDeptName(docInfoJson.getString("deptName"));
                docInfo.setAcademicAchievements(docInfoJson.getString("academicAchievements"));
                docs.add(docInfo);
            }
        }
    }

    @FXML
    private void getTicket() {
        DocInfo docInfo = docsEle.getSelectionModel().getSelectedItem();
        ToolUtil.getTicket(docInfo, 100);
    }

    @FXML
    private void cancelTask() {
        DocInfo docInfo = docsEle.getSelectionModel().getSelectedItem();
        ToolUtil.stopGetTicket(docInfo);
    }

    public void setMsg(String msg) {
        if (StringUtil.isEmpty(msg)) {
            return;
        }
        List<String> msgs = CacheUtil.get("msgs");
        msgs.add("[" + DateUtil.now() + "] " + msg + "\n");
        if (msgs.size() >= 30) {
            msgs.remove(0);
        }
        msgstb.setLength(0);
        for (int i = msgs.size() - 1;i >= 0;i--) {
            msgstb.append(msgs.get(i));
        }
        msgEle.setText(msgstb.toString());
    }

    @FXML
    @FXRedirect()
    public String appointTask() {
        DocInfo docInfo = docsEle.getSelectionModel().getSelectedItem();
        CacheUtil.putShortTime("appoint", docInfo);
        return "AppointTaskController";
    }

    @FXML
    private void cancelAppoint() {
        DocInfo docInfo = docsEle.getSelectionModel().getSelectedItem();
        CacheUtil.remove("appoint" + docInfo.getDocId());
        String scheduleStartId = CacheUtil.get("scheduleStartId" + docInfo.getDocId());
        String scheduleEndId = CacheUtil.get("scheduleEndId" + docInfo.getDocId());
        if (StringUtil.isNotEmpty(scheduleStartId)) {
            CronUtil.remove(scheduleStartId);
        }
        if (StringUtil.isNotEmpty(scheduleEndId)) {
            CronUtil.remove(scheduleEndId);
        }
        setMsg("取消预约成功");
    }

    @FXML
    private void allGetTicket() {
        DocInfo docInfo = docsEle.getSelectionModel().getSelectedItem();
        int timeout = 180000;
        ToolUtil.getTicket(docInfo, timeout);
        setMsg("每隔" + (timeout/1000) + "秒检查是否有票");
    }

    @FXML
    @FXRedirect
    public String updateConfig() {
        return "ConfigController";
    }

}
